#include "linked_stack.h"
#include <stdio.h>
#include <stdlib.h>


/**
 * @brief 栈初始化
 * @param stack 栈
 */
void LinkedStackInit(LinkedStack_t *stack)
{
    stack->top = NULL;
}

/**
 * @brief 判断栈是否为空
 * @param stack 栈
 * @return 栈空返回True，否则返回False
 */
bool LinkedStackIsEmpty(const LinkedStack_t *stack)
{
    return stack->top == NULL;
}

/**
 * @brief 入栈
 * @param stack 栈
 * @param data 入栈的数据
 * @return {@LinkedSackStatus_t}
 */
LinkedSackStatus_t LinkedStackPush(LinkedStack_t *stack, const BrowserData_t *data)
{
    StackNode_t *newNode = malloc(sizeof(StackNode_t));
    if (newNode == NULL) {
        return LINKED_STACK_FAIL;
    }
    newNode->data = *data;
    newNode->next = stack->top;
    stack->top = newNode;

    return LINKED_STACK_SUCCESS;
}

/**
 * @brief 出栈
 * @param stack 栈
 * @param data 出栈的数据
 * @return {@LinkedSackStatus_t}
 */
LinkedSackStatus_t LinkedStackPop(LinkedStack_t *stack, BrowserData_t *data)
{
    if (LinkedStackIsEmpty(stack)) {
        return LINKED_STACK_FAIL;
    }

    StackNode_t *temp = stack->top;
    *data = temp->data;
    stack->top = temp->next;
    free(temp);
    return LINKED_STACK_SUCCESS;
}


/**
 * @brief 获取顶栈的数据
 * @param stack 栈
 * @param data 顶栈的数据
 * @return {@LinkedSackStatus_t}
 */
LinkedSackStatus_t LinkedStackGetTop(const LinkedStack_t *stack, BrowserData_t *data)
{
    if (LinkedStackIsEmpty(stack)) {
        return LINKED_STACK_FAIL;
    }
    *data = stack->top->data;
    return LINKED_STACK_SUCCESS;
}

void LinkedStackDestroy(LinkedStack_t *stack)
{
    while (stack->top) {
        StackNode_t *curr = stack->top;
        stack->top = stack->top->next;
        free(curr);
    }
}